const express = require('express');
const bodyParser = require('body-parser');
const axios = require('axios');

const app = express();
const PORT = 3000;

// 解析 JSON 请求体
app.use(bodyParser.json());

// 接收消息的接口
app.post('/message', async (req, res) => {
  const message = req.body;

  console.log('收到消息:', message);
  if (message.type == '11041') {
    try {
      // 构造发送的参数
      const sendMessagePayload = {
        data: {
          conversation_id: 'R:10863460465942250',
          content: '已收到消息，自动回复',
        },
        type: 11029,
      };
      if (message.data.sender != '1688856833567179') {
        // 发送到本地的发消息接口
        const response = await axios.post('http://localhost:1998', sendMessagePayload);
        console.log(message.data.at_list, '@的人');

        console.log('消息已发送:', response.data);
      }
    } catch (error) {
      console.error('发送消息失败:', error);
      res.status(500).json({
        status: 'error',
        message: '发送消息失败',
        error: error.message,
      });
    }
  }

  res.json({
    status: 'success',
    data: JSON.parse(JSON.stringify(message)).data,
  });
});

const server = app.listen(
  {
    port: PORT,
    host: '127.0.0.1',
    exclusive: false, // 允许多个进程共享这个端口
  },
  () => {
    console.log(`服务器运行在 http://localhost:${PORT}`);
  }
);

server.on('error', (err) => {
  console.error('监听端口失败:', err);
});
